package com.dabaozhan.modules.wx_app.controller;

import com.alibaba.fastjson.JSON;
import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.Constants;
import com.dabaozhan.common.utils.OmsPage;
import com.dabaozhan.common.utils.RandomUtils;
import com.dabaozhan.common.utils.Utils;
import com.dabaozhan.modules.wx_app.base.ResponseDto;
import com.dabaozhan.modules.wx_app.entity.*;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.service.AccountLogService;
import com.dabaozhan.modules.wx_app.service.AccountService;
import com.dabaozhan.modules.wx_app.service.BankcardInfoService;
import com.dabaozhan.modules.wx_app.service.PayPassService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author houzhong
 * @date 2018-12-29 11:47
 */
@Api(value = "打包站用户接口", description = "打包站用户接口")
@RestController
@RequestMapping("/wx_app")
public class AccountController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountController.class);

    /**账户*/
    @Autowired
    private AccountService accountService;

    /**账户日志*/
    @Autowired
    private AccountLogService accountLogService;

    /**支付密码*/
    @Autowired
    private PayPassService payPassService;

    /**银行卡*/
    @Autowired
    private BankcardInfoService bankcardInfoService;

    @ApiOperation(value = "账户查询")
    @RequestMapping(value = "/accountInfo")
    public String accountInfo(String userId) {
        ResponseDto<AccountEntity> responseDto = new ResponseDto<AccountEntity>();
        try {
            AccountEntity v = accountService.findByUserId(userId);
            if (v != null) {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(v);
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_400);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("账户查询发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("账户查询发生异常:{}-返回结果:{}",JSON.toJSONString(userId),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "账户提现")
    @RequestMapping(value = "/toPutForward")
    public String toPutForward(AccountEntity v) {
        ResponseDto<AccountLogEntity> responseDto = new ResponseDto<AccountLogEntity>();
        try {
            PayPassEntity passVo = payPassService.findByPayUserId(v.getUserId());
            if (passVo != null) {
                String password = Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY);
                if (passVo.getPassword().equals(password)) {
                    AccountEntity accountVo = accountService.findByUserId(v.getUserId());
                    if (accountVo != null) {
                        //修改金额
                        accountVo.setAmount(accountVo.getAmount() - v.getAmount());
                        accountService.updateSiteAccount(accountVo);
                        //用户银行卡信息
                        BankcardInfoEntity bankcardInfo = bankcardInfoService.findByUserId(v.getUserId());
                        if (bankcardInfo != null) {
                            //操作日志
                            AccountLogEntity logVo = new AccountLogEntity();
                            //账户之前余额
                            logVo.setAmount(accountVo.getAmount());
                            //金额
                            logVo.setPrice(v.getAmount());
                            //用户id
                            logVo.setUserId(v.getUserId());
                            //账户id
                            logVo.setAccountId(accountVo.getId());
                            //类型 1 充值 2 提现 3 支出 4 收入
                            logVo.setBusinessType("2");
                            //提现操作状态，1 未操作 2 已操作
                            logVo.setType(1);
                            //业务编号
                            logVo.setAccountNumber(RandomUtils.random6());
                            //logVo.setBusinessNumber(RandomUtils.random6());
                            //所属人名称
                            logVo.setBankName(bankcardInfo.getBankName());
                            //手机号
                            logVo.setPhone(bankcardInfo.getPhone());
                            //所属支行
                            logVo.setBankCardName(bankcardInfo.getBankCardName());
                            //银行卡号
                            logVo.setBankCardNumber(bankcardInfo.getBankCardNumber());
                            //日志
                            accountLogService.saveSiteAccountLog(logVo);
                            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                            responseDto.setResult(logVo);
                        } else {
                            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_402);
                        }
                    }
                }else {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_501);
                }
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_502);
            }
        } catch (RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("账户体现发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("账户体现发生异常:{}-返回结果:{}",JSON.toJSONString(v),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "账户明细查询")
    @RequestMapping(value = "/accountList")
    public String accountList(AccountEntity v,Integer page,Integer size) {
        ResponseDto<OmsPage<AccountEntity>> responseDto = new ResponseDto<OmsPage<AccountEntity>>();
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("userId",v.getUserId());
            params.put("businessType",v.getBusinessType());
            params.put("page",(page - 1) * size);
            params.put("size",size);

            OmsPage<AccountEntity> pages = accountService.findByAccount(params);
            if (pages.getResult().size()>0) {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(pages);
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_400);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("账户明细查询发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("账户明细查询发生异常:{}-返回结果:{}",JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }
}
